<template>
  <div class="school-contact">
    <!-- 导航栏 -->
    <el-menu mode="horizontal">
      <el-menu-item index="departments" @click="changeTab('departments')"
        >学校部门信息</el-menu-item
      >
      <el-menu-item
        index="parent-registration"
        @click="changeTab('parent-registration')"
        >家长信息登记</el-menu-item
      >
    </el-menu>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 学校部门信息 -->
      <div v-if="activeTab === 'departments'">
        <h2>学校部门信息</h2>
        <div
          class="department-info"
          v-for="department in departments"
          :key="department.id"
        >
          <el-descriptions :title="department.name" border>
            <el-descriptions-item label="联系电话">{{
              department.phone
            }}</el-descriptions-item>
            <el-descriptions-item label="邮箱地址">{{
              department.email
            }}</el-descriptions-item>
            <el-descriptions-item label="办公时间">{{
              department.officeHours
            }}</el-descriptions-item>
            <el-descriptions-item label="办公地点">{{
              department.address
            }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>

      <!-- 家长信息登记 -->
      <div v-if="activeTab === 'parent-registration'">
        <h2>家长信息登记</h2>
        <el-form
          :model="parentRegistrationForm"
          :rules="parentRegistrationRules"
          ref="parentRegistrationForm"
          label-width="20vw"
        >
          <el-form-item label="学生姓名" prop="studentName">
            <el-input v-model="parentRegistrationForm.studentName"></el-input>
          </el-form-item>
          <el-form-item label="学生学号" prop="studentId">
            <el-input v-model="parentRegistrationForm.studentId"></el-input>
          </el-form-item>
          <el-form-item label="家长姓名" prop="name">
            <el-input v-model="parentRegistrationForm.name"></el-input>
          </el-form-item>
          <el-form-item label="家长联系电话" prop="phone">
            <el-input v-model="parentRegistrationForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="家长邮箱地址" prop="email">
            <el-input v-model="parentRegistrationForm.email"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button :type="submitButtonColor" @click="submitForm">{{
              submitButtonText
            }}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
import { mapState } from "vuex";

export default {
  computed: {
    ...mapState(["user","activeTab"]),
    submitButtonText() {
      return this.hasData ? "更新" : "提交";
    },
    submitButtonColor() {
      return this.hasData ? "warning" : "primary";
    },
  },
  created() {
    // 在组件创建时加载学校部门信息和家长信息
    this.fetchSchoolDepartment();
  },
  data() {
    return {
      // activeTab: "departments",
      departments: [],
      parentRegistrationForm: {
        name: "",
        phone: "",
        email: "",
        studentName: "",
        studentId: "",
      },
      parentRegistrationRules: {
        // 表单验证规则
        name: [{ required: true, message: "请输入家长姓名", trigger: "blur" }],
        phone: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              const phoneRegex = /^1\d{10}$/;
              if (!phoneRegex.test(value)) {
                callback(new Error("请输入有效的11位手机号码"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        studentName: [
          { required: true, message: "请输入学生姓名", trigger: "blur" },
        ],
        studentId: [
          { required: true, message: "请输入学生学号", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              const studentIdRegex = /^\d+$/;
              if (!studentIdRegex.test(value)) {
                callback(new Error("学生学号只能是数字"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        email: [
          { required: false, message: "请输入邮箱地址", trigger: "blur" },
          { type: "email", message: "邮箱地址格式不正确", trigger: "blur" },
        ],
      },
      hasData: false, // 追踪是否已经存在数据
    };
  },
  watch: {
    user: {
      handler(newVal, oldVal) {
        if (newVal.ybUserId) {
          this.fetchParentInfo();
        }
      },
      immediate: true, // 立即执行一次
    },
  },
  methods: {
    changeTab(tab) {
      this.$store.commit('changeActiveTab',tab);
      // 切换导航栏标签页
    },
    fetchSchoolDepartment() {
      // 获取学校部门信息
      this.$http
        .get("/departments/all")
        .then((response) => {
          this.departments = response.data.map((department) => ({
            name: department.depName,
            phone: department.depPhone,
            email: department.depEmail,
            officeHours: department.depTime,
            address: department.depAddress,
          }));
        })
        .catch((error) => {
          console.error("Error fetching departments:", error);
        });
    },
    fetchParentInfo() {
      // 获取家长信息
      this.$http
        .get(`/parents/${this.user.ybUserId}`)
        .then((res) => {
          let parentInfo = res.data;
          this.hasData = !!parentInfo.parentChildId;
          if (this.hasData) {
            this.updateParentRegistrationFormValues(parentInfo);
          }
        })
        .catch((error) => {
          console.error("loading parent info error");
        });
    },
    updateParentRegistrationFormValues(parentInfo) {
      // 更新家长信息表单的值
      this.parentRegistrationForm.name = parentInfo.parentName;
      this.parentRegistrationForm.phone = parentInfo.parentPhone;
      this.parentRegistrationForm.email = parentInfo.parentEmail;
      this.parentRegistrationForm.studentId = parentInfo.parentChildId;
      this.parentRegistrationForm.studentName = parentInfo.parentChildName;
    },
    submitForm() {
      // 提交家长信息表单
      this.$refs.parentRegistrationForm.validate((valid) => {
        if (valid) {
          const info = this.buildInfoObject();
          this.submitInfo(info);
        } else {
          this.$message.error("表单校验失败");
        }
      });
    },
    buildInfoObject() {
      // 构建家长信息对象
      return {
        ybUserId: this.user.ybUserId,
        ybUserName: this.user.username,
        parentChildId: this.parentRegistrationForm.studentId,
        parentChildName: this.parentRegistrationForm.studentName,
        parentName: this.parentRegistrationForm.name,
        parentPhone: this.parentRegistrationForm.phone,
        parentEmail: this.parentRegistrationForm.email,
        parentState: true,
      };
    },
    submitInfo(info) {
      // 提交家长信息
      // if (this.submitButtonText === "提交") {
      //   this.$http
      //     .post("/parents/add", info)
      //     .then(() => {
      //       this.$message.success("提交成功");
      //     })
      //     .catch((error) => {
      //       console.log("Error Add Parent", error);
      //       this.$message.error('提交失败')
      //     });
      // } else if (this.submitButtonText === "更新") {
        this.$http
          .put("/parents/update", info)
          .then(() => {
            this.$message.success("操作成功");
            this.hasData=true;
            this.$store.dispatch("getUser", this.$store.state.user.ybUserId);//更新vuex中user数据
          })
          .catch((error) => {
            console.log("Error Update Parent", error);
            this.$message.error('操作失败')
          });
      // }
    },
  },
};
</script>


<style scoped>
.school-contact {
  padding: 20px;
}

.main-content {
  margin-top: 20px;
}
.department-info {
  margin: 20px;
  border-radius: 20px;
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .school-contact {
    padding: 10px;
  }

  .department-card {
    padding: 10px;
  }
}
</style>
